﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using System.Collections.Specialized;
using System.Reflection;
using System.Collections;

namespace CLFramework.MSSqlExport
{
    public static class SmoExtensions
    {

        public static string GenerateScript(this IScriptable scriptableObj, ScriptingOptions options)
        {
            return ScriptBuilder(scriptableObj.Script, options);
        }

        public static string GenerateDataScript(this Table table, ScriptingOptions options)
        {
            MethodInfo method = typeof(Table).GetMethod("ScriptDataInternal", BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
            IEnumerable script = method.Invoke(table, new object[] { options }) as IEnumerable;
            StringBuilder scripts = new StringBuilder();
            scripts.AppendLine("GO");
            IEnumerator s = script.GetEnumerator();
            while (s.MoveNext())
            {
                scripts.AppendLine(s.Current.ToString());
            }
            return scripts.ToString();
        }

        public static StringCollection ScriptCreate(this SqlSmoObject obj, ScriptingOptions options)
        {
            StringCollection script = new StringCollection();
            MethodInfo method = typeof(SqlSmoObject).GetMethod("ScriptCreateInternal", BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
            method.Invoke(obj, new object[] { script, options });
            return script;
        }

        public static string GenerateScript(this Scripter scripter, SqlSmoObject obj)
        {
            StringBuilder scripts = new StringBuilder();
            scripts.AppendLine("GO");
            StringCollection sc = scripter.Script(new SqlSmoObject[] { obj });
            foreach (String s in sc)
            {
                scripts.AppendLine(s);
            }
            return scripts.ToString();
        }

        static string ScriptBuilder(Func<ScriptingOptions, StringCollection> script, ScriptingOptions options)
        {
            try
            {
                StringBuilder scripts = new StringBuilder();
                StringCollection sc = script(options);
                foreach (String s in sc)
                {
                    scripts.AppendLine(s);
                    scripts.AppendLine("GO");
                }
                return scripts.ToString();
            }
            catch (Exception ex)
            {
                return "错误：" + ex.InnerException.InnerException.Message;
            }
        }

    }
}
